// ==UserScript==
// @name         メガミエンゲイジ！extra
// @description  ブラウザゲーム「メガミエンゲイジ！」のプレイをより快適にするためのツール
// @include      http://*.megamiengage.com/*
// @author       Kaede
// @version      0.3
// @downloadURL  https://megamiengage-extra.googlecode.com/svn/trunk/megamiengage-extra.user.js
// @updateURL    https://megamiengage-extra.googlecode.com/svn/trunk/megamiengage-extra.meta.js
// ==/UserScript==

function Main() {
	
	/* Javascript Common begin */
	
	function reloadpage() {
			var url = window.location.toString();
			var anchor_pos = url.indexOf('#');
			if (-1 != anchor_pos) {
				url = url.substring(0, anchor_pos);
			}
			window.location.replace(url);
	}
	
	function substr00(text) {
		return ('00' + text).toString().substr(-2);
	}
	
	Array.prototype.join2 = function(l,r,m) {
		var m = m || '';
		var txt = '';
		for (var i=0;i<this.length;i++) {
				txt += l + this[i] + r;
				if ( i > 0 ) { txt += m; }
		}
		return txt;
	}
	
	function getTimeText(totalsec) {
		totalsec = Math.floor(totalsec);
		var day = Math.floor(totalsec/86400);
		var hour = Math.floor((totalsec-day*86400)/3600);
		var minute = Math.floor((totalsec-day*86400-hour*3600)/60);
		var second = totalsec-day*86400-hour*3600-minute*60;
		return ((day>0)?day+':':'')+substr00(hour)+':'+substr00(minute)+':'+substr00(second);
	}
	
	function getDateText(d) {
		return d.getFullYear() + '-' + substr00(d.getMonth()+1) + '-' + substr00(d.getDate()) + ' ' + substr00(d.getHours()) + ':' + substr00(d.getMinutes()) + ':' + substr00(d.getSeconds());
	}
	
	function getSeconds(datestring) { // 00:00:00
		var t = datestring.match(/(\d+)\:(\d+)\:(\d+)/);
		return parseInt(t[1])*3600 + parseInt(t[2])*60 + parseInt(t[3]);
	}
	
	function getDate(datestring) { // 1970-1-1 00:00:00 -> 1970,1,1,00:00:00
		return new Date(Date.parse(datestring.replace(/[\- ]/g,',')));
	}
	
	function calcTimeDiff(date1, date2) {
		return getTimeText( Math.abs( getDate(date2).getTime() - getDate(date1).getTime() ) );
	}
	
	function calcDate(datastring, offset) {
		return getDateText( new Date( getDate(datastring).getTime() + offset*1000 ) );
	}
	
	function formatNumber(number) {
		var n = number.toString().split(".");
		n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
		return n.join(".");
	}
	
	function getCoord( href ) {
		var coord = href.match(/x=([\-0-9]+)&y=([\-0-9]+)/i);
		return coord;
	}
	
    function getDistance(x, y) {
    	return Math.sqrt(Math.pow(CurrentVillage.x - x, 2) + Math.pow(CurrentVillage.y - y, 2)).toFixed(2);
    }
    
	function debug( object ) {
		alert( JSON.stringify(object) );
	}
	
	/* Javascript Common end */
		
	/* Megamiengage Common begin */
	var CurrentVillage = (function () {
		var $li = j$(j$('#basepoint_drop .hover li.on, .basepoint_drop .hover li.on')[0]);
		var Index = j$('#basepoint_drop .hover li, .basepoint_drop .hover li').index($li);
		var Name = $li.text();
		var coord = j$('.gnavi04 a').attr( 'href' ).match(/x=([\-0-9]+)&y=([\-0-9]+)/i);
		return {
			'name'       : Name,
			'index'      : Index,
			'coordinate' : coord[1]+','+coord[2],
			'x'          : coord[1],
			'y'          : coord[2]
		};
	})();
	
	var My = {
		'name'     : j$('.profile_text').text().trim(),
		'alliance' : j$('.alliance_txt').text().trim(),
		'karisuma' : j$('#charisma_resource').text().match(/\/(\d+)/)[1],
	};
	
	var Server = {
		'version'  : location.hostname.match(/(\w)\d+/)[1], // m=mixi版；s=公式版
		'world'    : location.hostname.match(/\w(\d+)/)[1],
		'getTime'  : function() { return j$('#server_time').text(); },
		'season'   : -1,
	};
	
	var mana = {
		now : [],
		rate : [],
		rate_basic : [],
		rate_gain : [],
		max : [],
		name : ['風', '火', '水', '土']
	};
	
	function createExtraMenu(object, arr) {
		var html='';
		j$.each(arr, function(index, value) {
			html += '<li><a href="' + value[1] + '">' + value[0] + '</a></li>';
		});
		if ( html.length > 0 ) {
			var $container = j$(object);
			var top = $container.offset().top + $container.height();
			var left = $container.offset().left;
			$container.html('<div class="extra_menu">' + $container.html() + '<ul style="top:'+top+'px;left:'+left+'px">' + html + '</ul>' + '</div>');
		}
	}
	
	j$('head').append( '<style>.extra { color:red; }</style>' );
	j$('head').append( '<style>.extra_menu { display:inline;} .extra_menu ul {background: #EEEEEE;border: 1px solid #B4B4B4;box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);display: none;margin: 0;padding: 0;position: absolute;z-index: 1000;}.extra_menu ul li {float: none;margin: 0;padding: 0;}.extra_menu ul a {font-size:12px !important;padding: 3px 10px;display:block;text-align:left;font-weight:normal !important;} .extra_menu:hover > ul { display: block; } .extra_menu ul a:hover { background-color: #FF078E !important; color: #FFFFFF !important;}</style>' );
	
	
	var DesignMode = false;
	
	/* Megamiengage Common end */
	
	/* Settings begin */
	
	var optionlist = {
		'共通' : {
			'manatooltip'		: [ '資源のツールチップに合計生産量と満タンまでの時間を表示する', true ],
			'navimenu'			: [ 'ナビゲーションボタンにドロップダウンメニューを追加する', true ],
			'basepointmenu'		: [ '拠点一覧メニューを改善する', true ],
		},
		'ホーム' : {
			'facilitystatus'	: [ 'マップ上に施設の作業状況を表示する', true ],
		},
		'施設' : {
			'facilitycost'		: [ '必要な資源が不足している時、必要量に達するまでの時間を表示する', true ],
			'facilitynew'		: [ '平地の建設画面を改善する', true ],
			'facilitydata'		: [ '施設のレベルアップデータを表示する', true ],
			'mahoujin'			: [ '魔法陣のコスト回収時間を表示する（土のマナの価値は他のマナの50%として計算される）', true, 0.5 ],
			'henkanro'			: [ 'マナ変換炉の取引機能を改善する', true ],
		},
		'デッキ' : {
			'cardset'			: [ 'セット先の初期状態を現在の拠点にする', true ],
			'cardrecovery'		: [ 'HPとテンションの回復時間を表示する', true ],
			'statuspoint'		: [ 'ステータス強化画面の振り分けボタンを改善する', true ],
		},
		'戦闘' : {
			'attacktime'		: [ '攻撃確認画面に出発時間計算機能を追加する', true ],
			//'expedition'		: [ '地図画面に遠征記録機能を追加する', true ],
		},
		'同盟' : {
			'allyranking'		: [ '同盟トップ画面を改善する', true ],
		},
		'リンク' : {
			'textcoord'			: [ '掲示板やメールのテキスト中に含まれる座標にリンクを貼る', true ],
			'texturl'			: [ '掲示板やメールのテキスト中に含まれるURLにリンクを貼る', true ],
			'coordmenu'			: [ '座標のリンクにドロップダウンメニューを追加する', true ],
			'usermenu'			: [ 'マスターのリンクにドロップダウンメニューを追加する', true ],
			'skipextlink'		: [ '外部サイトへの遷移確認をスキップする', true ],
		},
		'クエスト' : {
			'questoverflow'		: [ '倉庫の空き容量以上の報酬を受け取る時、確認メッセージを表示する', true ],
		},
		'その他' : {
			'hidecp'			: [ '便利機能を隠す', false ],
		}
	};
	
	var defaultoptions = {};
	j$.each(optionlist, function(optiongroupname, optiongroup) {
		j$.each(optiongroup, function(optionkey, option) {
			defaultoptions[optionkey] = option[1];
		});
	});
	
	function clsStorage () {
		var StorageKey = 'megamiengage-extra-' + My.name;
		
		function load () {
			var value;
			var item = window.localStorage.getItem( StorageKey );
			if ( item == null) {
				value = { };
			} else {
				try {
					value = JSON.parse( item );
				} catch (exception) {
					value = { };
				}
			}
			return value;
		}
		
		this.save = function () {
			window.localStorage.setItem( StorageKey, JSON.stringify( this.values ) );
		}
		
		this.values = load();
		
		this.get = function ( key, defaultvalue ) {
			if ( key in this.values ) { return this.values[key]; } else { return defaultvalue || {}; }
		}
		
		this.hasKey = function ( key ) {
			return ( key in this.values );
		}
		
		this.set = function ( key, value ) {
			this.values[key] = value;
			this.save();
		}
　}

	var Storage = new clsStorage();
	
	function checkOption( key ) {
		if ( 'options' in Storage.values && key in Storage.values['options'] ) {
			return Storage.values['options'][key];
		} else {
			return defaultoptions[key];
		}
	}
	
	var Contentpage = '';
	function checkContentpage( title ) {
		return ( Contentpage == title );
	}
	function createContentpage( title, content ) {
		if ( Contentpage == title ) {
			removeContentpage();
		} else {
			var wrapper = '<div id="gray02Wrapper" class="clearfix settings">';
			wrapper += '<h2>' + title + '</h2>';
			wrapper += content;
			wrapper += '</div>';
			j$('#wrapper').children().hide();
			j$('#wrapper').append(wrapper);
			Contentpage = title;
		}
	}
	function removeContentpage() {
		Contentpage = '';
		j$('.settings').remove();
		j$('#wrapper').children().show();
	}
	
	var extraicon = '<img alt="" src="" />'
	
	j$('#header_contents ul').append('<li><a id="togglejs" href="javascript:void(0)" title="スクリプト設定">' + extraicon + '</a></li>');
	j$('#togglejs').css({
		'font-size'   : '12px',
		'font-weight' : 'bold',
		'color'       : 'white',
		'text-shadow' : '-1px 0 color, 0 1px color, 1px 0 color, 0 -1px color'.replace( /color/g, Storage.get('enable')?'blue':'blue' ),
		'float'       : 'right',
		'line-height':'16px',
		'vertical-align':'middle',
	});
	j$('#togglejs img').css({
		'vertical-align':'middle',
		'line-height':'16px'
	});
	
	j$('#togglejs').click(function() {
		if ( Server.version == 's' ) {
			delete optionlist['リンク']['skipextlink'];
		}
		if ( !checkContentpage('メガミエンゲイジ！extra') ) {
			var wrapper = '';
			wrapper += '<table class="commonTables">';
			wrapper += '<colgroup><col class="w30"><col></colgroup>';
			wrapper += '<tbody>';
			wrapper += '<tr><th class="mainTtl" colspan="2">機能設定</th></tr>';
			var options = Storage.get( 'options' );
			j$.each(optionlist, function(optiongroupname, optiongroup) {
				wrapper += '<tr><th class="ttl4" colspan="2">' + optiongroupname + '</th></tr>';
				j$.each(optiongroup, function(optionkey, option) {
					wrapper += '<tr><td class="center"><input class="opt" type="checkbox" value="' + optionkey + '"' + ( checkOption(optionkey) ? ' checked' : '' ) + '></td>';
					wrapper += '<td>' + option[0] + '</td></tr>';
				});
			});
			wrapper += '</tbody></table>';
			wrapper += '<input id="save" type="button" value="保存">';
			wrapper += '<input id="cancel" type="button" value="キャンセル">';
			wrapper += '<input id="reset" type="button" value="リセット">';
			
			wrapper += '<table class="commonTables"><colgroup><col class="w100"><col></colgroup><tbody>';
			wrapper += '<tr><th class="mainTtl" colspan="2">バージョン情報</th></tr>';
			wrapper += '<tr><th class="ttl5">スクリプト名</th><td>メガミエンゲイジ！extra</td></tr>';
			wrapper += '<tr><th class="ttl5">バージョン</th><td>0.2</td></tr>';
			wrapper += '<tr><th class="ttl5">ホームページ</th><td><a href="https://code.google.com/p/megamiengage-extra" target="_blank">https://code.google.com/p/megamiengage-extra</a></td></tr>';
			wrapper += '</tbody></table>';
			if (DesignMode) {
				wrapper += '<table class="commonTables"><colgroup><col class="w100"><col></colgroup><tbody>';
				wrapper += '<tr><th class="mainTtl" colspan="2">セーブデータ</th></tr>';
				wrapper += '<tr><th class="ttl5">localStorage</th><td><pre>' + JSON.stringify( Storage.values, null, 2 ) + '</pre></td></tr>';
				wrapper += '</tbody></table>';
			}
			createContentpage( 'メガミエンゲイジ！extra', wrapper );
			
			j$('#save').click(function() {
				var $opt = j$('input.opt');
				var options = {};
				for ( var i = 0; i < $opt.length; i++ ) {
					if ( $opt[i].checked != defaultoptions[$opt[i].value] ) { options[$opt[i].value] = $opt[i].checked; }
				}
				Storage.set('options',options);
				reloadpage();
			});
			j$('#cancel').click(function() {
				removeContentpage();
			});
			j$('#reset').click(function() {
				var defaultoptions = getDefaultOptions();
				var $opt = j$('input.opt');
				var options = [];
				for ( var i = 0; i < $opt.length; i++ ) {
					$opt[i].checked = ( defaultoptions.indexOf($opt[i].value) != -1 );
				}
			});
		} else {
			removeContentpage();
		}
		return false;
	});
	
	if( location.pathname == '/user/' && location.search == '' ) {
		var $l = j$('.commonTables > tbody > tr:gt(17)');
		var info = {};
		for ( var i=0; i<$l.length; i++ ) {
			var id = j$('a',$l[i]).attr('href').match(/id=(\d+)/i)[1];
			var coord = j$('td:nth-child(2)',$l[i]).text();
			info[id] = coord;
		}
		Storage.set( 'villagesinfo', info );
	}
	
	/* Settings end */
	
	/* Megamiengage Main begin */
	
	if ( true || Storage.get('enable', true) ) {
		if ( checkOption('navimenu') ) {
			var navmenu = {
				'm' : {
					'ホーム' : {
						'ホームトップ':'/facility/castle.php',
						'オートマタ管理':'/facility/unit_status.php',
						'領地管理':'/facility/territory_status.php',
						'攻撃':'/facility/castle_send_troop.php',
						'開発設定':'/card/domestic_setting.php',
						'スキル':'/skill/index.php',
						'デッキ':'/card/deck.php',
						'召喚くじ履歴':'/busyodas/busyodas_history.php',
					},
					'デッキ' : {
						'ホームトップ':'/facility/castle.php',
						'オートマタ管理':'/facility/unit_status.php',
						'領地管理':'/facility/territory_status.php',
						'攻撃':'/facility/castle_send_troop.php',
						'開発設定':'/card/domestic_setting.php',
						'スキル':'/skill/index.php',
						'デッキ':'/card/deck.php',
						'召喚くじ履歴':'/busyodas/busyodas_history.php',
					},
					'同盟' : {
						'同盟トップ':j$('.gnavi03 a').attr( 'href' ),
						'ランキング詳細':'/alliance/ranking.php',
						'勢力リスト':'/alliance/dependency.php',
						'同盟ログ':'/alliance/alliance_log.php',
						'掲示板':'/bbs/topic_view.php',
						'同盟ひとこと掲示板':'/alliance/chat_view.php',
						'管理':'/alliance/manage.php',
						'配下同盟管理':'/alliance/manage_dep.php',
						'同盟募集':'/alliance/recruit.php',
						'同盟希望':'/alliance/join_bbs.php',
					},
					'地図' : {
						'11×11':'/map.php?x=' + CurrentVillage.x + '&amp;y=' + CurrentVillage.y + '&amp;type=1',
						'15×15':'/map.php?x=' + CurrentVillage.x + '&amp;y=' + CurrentVillage.y + '&amp;type=2',
						'20×20':'/map.php?x=' + CurrentVillage.x + '&amp;y=' + CurrentVillage.y + '&amp;type=3',
						'51×51':'/map.php?x=' + CurrentVillage.x + '&amp;y=' + CurrentVillage.y + '&amp;type=4',
					},
					'勢力' : {
						'勢力状況':'/force/force_status.php',
						'勢力ランキング':'/force/force_ranking.php',
						'達成報酬':'/force/force_reward.php',
					},
					'ランキング' : {
						'総合':'/',
						'発展度':'/user/ranking.php?m=population',
						'攻撃':'/user/ranking.php?m=attack',
						'防御':'/user/ranking.php?m=defense',
						'撃破スコア':'/ranking.php?m=attack_score',
						'防衛スコア':'/user/ranking.php?m=defense_score',
						'同盟':'/alliance/list.php',
						'制圧':'/alliance/npc_mastery_ranking.php',
						'週間ランキング':'/user/weekly_ranking.php',
						'勢力攻撃':'/user/ranking.php?m=force_attack',
						'勢力防御':'/user/ranking.php?m=force_defense',
						'勢力週間ランキング':'/user/weekly_ranking.php?m=force',
					},
					'報告書' : {
						'全て':'/report/list.php',
						'攻撃':'/report/list.php?m=attack&amp;u=',
						'防御':'/report/list.php?m=defence&amp;u=',
						'偵察':'/report/list.php?m=scout&amp;u=',
						'破壊':'/report/list.php?m=fall&amp;u=',
						'援軍':'/report/list.php?m=reinforcement&amp;u=',
						'同盟':'/report/list.php?m=alliance&amp;u=',
					},
					'メール' : {
						'受信箱':'/message/inbox.php',
						'送信履歴':'/message/outbox.php',
						'新規作成':'/message/new.php',
						'ブラックリスト':'/message/black_list/black_list.php',
					},
				},
				's' : {
					'拠点' : {
						'拠点開発':'/village.php',
						'拠点':'/facility/castle.php',
						'開発設定':'/card/domestic_setting.php',
						'領地管理':'/facility/territory_status.php',
					}, 
					'バトル' : {
						'デッキ':'/card/deck.php',
						'部隊管理':'/facility/unit_status.php',
						'攻撃':'/facility/castle_send_troop.php',
						'開発設定':'/card/domestic_setting.php',
						'スキル':'/skill/index.php',
					},
					'同盟' : {
						'同盟情報':j$('.gnavi03 a').attr( 'href' ),
						'同盟員一覧':'/alliance/ranking.php',
						'配下同盟':'/alliance/dependency.php',
						'同盟ログ':'/alliance/alliance_log.php',
						'掲示板':'/bbs/topic_view.php',
						'同盟ひとこと掲示板':'/alliance/chat_view.php',
						'同盟管理':'/alliance/manage.php',
						'配下同盟管理':'/alliance/manage_dep.php',
						'同盟募集':'/alliance/recruit.php',
						'同盟希望':'/alliance/join_bbs.php',
					},
					'地図' : {
						'11×11':'/map.php?x=' + CurrentVillage.x + '&amp;y=' + CurrentVillage.y + '&amp;type=1',
						'15×15':'/map.php?x=' + CurrentVillage.x + '&amp;y=' + CurrentVillage.y + '&amp;type=2',
						'20×20':'/map.php?x=' + CurrentVillage.x + '&amp;y=' + CurrentVillage.y + '&amp;type=3',
						'51×51':'/map.php?x=' + CurrentVillage.x + '&amp;y=' + CurrentVillage.y + '&amp;type=4',
					},
					'勢力' : {
						'勢力状況':'/force/force_status.php',
						'勢力ランキング':'/force/force_ranking.php',
						'達成報酬':'/force/force_reward.php',
					},
					'ランキング' : {
						'総合':'/',
						'発展度':'/user/ranking.php?m=population',
						'攻撃':'/user/ranking.php?m=attack',
						'防御':'/user/ranking.php?m=defense',
						'撃破スコア':'/ranking.php?m=attack_score',
						'防衛スコア':'/user/ranking.php?m=defense_score',
						'同盟':'/alliance/list.php',
						'制圧':'/alliance/npc_mastery_ranking.php',
						'週間ランキング':'/user/weekly_ranking.php',
						'勢力攻撃':'/user/ranking.php?m=force_attack',
						'勢力防御':'/user/ranking.php?m=force_defense',
						'勢力週間ランキング':'/user/weekly_ranking.php?m=force',
					},
					'報告書' : {
						'全て':'/report/list.php',
						'攻撃':'/report/list.php?m=attack&amp;u=',
						'防御':'/report/list.php?m=defence&amp;u=',
						'偵察':'/report/list.php?m=scout&amp;u=',
						'破壊':'/report/list.php?m=fall&amp;u=',
						'援軍':'/report/list.php?m=reinforcement&amp;u=',
						'同盟':'/report/list.php?m=alliance&amp;u=',
					},
					'メール' : {
						'受信箱':'/message/inbox.php',
						'送信履歴':'/message/outbox.php',
						'新規作成':'/message/new.php',
						'ブラックリスト':'/message/black_list/black_list.php',
					},
				},
			}
			
			j$('#gNav_drop li').each(function() {
				var title = j$('a',this).attr('title');
				if ( title in navmenu[Server.version] ) {
					var ul='';
					j$.each(navmenu[Server.version][title], function(text, href) {
						ul += '<li><a href="' + href + '">' + text + '</a></li>';
					});
					if ( ul.length > 0 ) {
						j$(this).append('<ul>' + ul + '</ul>');
					}
				}
			});
			j$('#gNav_drop ul').css({
				'top'      : '60px',
				'z-index'  : '10000',
			});
			j$('#gNav_drop ul a').css('font-size', '12px');
		}
	
		// 拠点一覧メニュー
		if ( checkOption('basepointmenu') ) {
			j$('#basepoint_drop .hover li.on a, .basepoint_drop .hover li.on a').css({
				'font-weight' : 'bold',
				'cursor'      :'default'
			});
			var karisuma = [17,35,54,80,112,150,195,248,310];
			j$('#basepoint_drop .hover, .basepoint_drop .hover').each(function() {
				var $this = j$(this);
				var l = $this.children().length;
				for (var i=l-1;i<karisuma.length;i++) {
					if ( karisuma[i] <= My.karisuma ) {
						$this.append('<li class="gray"><a href="#">🔓 新拠点建設可能</a></li>');
					} else {
						$this.append('<li class="gray"><a href="#">🔒 カリスマ' + karisuma[i] + 'で解禁</a></li>');
						break;
					}
				}
			});
			j$('li.gray a').css({
				'color'  : 'gray',
				'cursor' : 'default'
			});
		}
			
		// 資源ツールチップ
		if ( checkOption('manatooltip') ) {
			var restitle = '';
			for (i=0;i<=3;i++) {
				var $res = j$('#header_resource>div:nth-child('+(i+1)+')');
				mana.rate[i] = parseInt(eval(j$('div.header',$res).text()));
				mana.rate_basic[i] = parseInt(j$('div.header',$res).text().match(/(\d+)/)[1]);
				mana.rate_gain[i]  = parseInt(j$('div.header .increase',$res).text());
				mana.now[i]  = parseInt(j$('span.now',$res).text());
				mana.max[i]  = parseInt(j$('.bottom span:last',$res).text());
				var tt = ( mana.max[i] - mana.now[i] ) / mana.rate[i] * 3600;
				
				restitle += mana.name[i] + 'のマナ\n' ;
				restitle += '・収集量: ' + mana.rate_basic[i] + '＋' + mana.rate_gain[i] + '＝' + mana.rate[i] + '\n' ;
				restitle += '・満タンまで: あと' + getTimeText(tt) + '\n' ;
				if ( i<3 ) { restitle += '\n' ; }
				if ( mana.now[i] == mana.max[i] ) {
					j$('div.header p',$res).text( '0' );
					//j$('div.bottom p',$res).css( 'color', 'red' );
					j$('div.bottom p .now',$res).hide().after('<span style="color:red">MAX</span>');
				}
			}
			j$('#header_resource > div:lt(4)').attr( 'title' , restitle );
		}
		if ( false && checkOption('manacolor') ) {
			for (i=0;i<=3;i++) {
				var r = parseInt((Math.max(mana.now[i],mana.max[i]/2)-mana.max[i]/2)/(mana.max[i]/2)*255);
				var g = 255-r;
				j$('#header_resource>div:nth-child('+(i+1)+') span.now').css('color','rgb('+r+','+g/2+',0)');
			}
		}
		
		////////////////////
		// ホーム
		////////////////////
		if ( location.pathname == '/village.php' ) {
			if ( checkOption('facilitystatus') ) {
				var indexcount = [];
				j$('#actionLog li').each(function() {
					var color = {
						'建設' : 'blue',
						'準備' : '#A52a2a',
						'削除' : 'red',
						'強化' : 'purple',
						'研究' : 'purple'
						};
					var status = '';
					var xy = '';
					
					if ( j$('a', this).length > 0 ) {
						xy = j$('a:first', this).attr('href').match(/x=([\-0-9]+)&y=([\-0-9]+)/i);
						status = j$(this).text().match( /(..)中/ )[1];
					} else {
						status = j$(this).text().match( /(防具|武器|研究)/ )[0];
						if ( status == '研究' ) {
							xy = j$('area[title*="錬金工房"]').attr('href').match(/x=([\-0-9]+)&y=([\-0-9]+)/i);
						} else {
							xy = j$('area[title*="' + status + '工房"]').attr('href').match(/x=([\-0-9]+)&y=([\-0-9]+)/i);
							status = '強化';
						}
					}
					
					var facilityindex = parseInt(xy[1])*7+parseInt(xy[2])+1;
					if ( facilityindex in indexcount ) { indexcount[facilityindex] += 1; } else { indexcount[facilityindex] = 1; }
					var $img = j$('img.map'+substr00(facilityindex));
					var $span = j$('<span>'+status+'中</span>').css({ 
						'font-size'   : '12px',
						'color'       : '#eee',
						'text-shadow' : '-1px 0 color, 0 1px color, 1px 0 color, 0 -1px color'.replace( /color/g, color[status] ),
						'top'         : $img.position().top  + 25 + indexcount[facilityindex] * 14,
						'left'        : $img.position().left + 20,
						'position'    : 'absolute',
						'z-index'     : '49'
					});
					j$('.mapOverlay').before($span);
				});
			}
		}
		
		////////////////////
		// 施設の情報
		////////////////////
		if( location.pathname.match( '\/facility\/(facility|castle|select_facility)\.php' ) ) {
			//コスト
			if ( checkOption('facilitycost') ) {
				j$('td.cost span.sep').html('<br>');
				var reqres = [];
				j$('td.cost').each(function() {
					var $reqres = j$('span:even', this);
					if ( $reqres.length < 4 ) { return; }
					for (i=0;i<=3;i++) {
						reqres[i] = parseInt($reqres[i].innerHTML);
						if ( reqres[i] > mana.now[i]) {
							var reqsec = ( reqres[i] - mana.now[i] ) / mana.rate[i] * 3600;
							$reqres[i].innerHTML += '(あと' + getTimeText(reqsec) + ')';
						}
					}
				});
			}
		}
		
		if( location.pathname.match( '\/facility\/(facility|castle)\.php' ) ) {
			if ( checkOption('facilitydata') ) {
				var FacilitiesData = {
					205 : {
						name : '本館',
						cost : [
							[0,1404,2570,4161,7102,9056,14384,22773,33562,44402,65122,95317,113458,150418,219008,294820,488220,839130,1307581,1901938],
							[0,546,1000,2081,3552,9056,14384,22773,33562,57559,84418,123558,154716,150418,219008,294820,488220,839130,1307581,1901938],
							[0,390,714,2081,3552,6037,9589,15183,22374,32890,48239,70605,154716,315878,492770,663345,827854,915414,1354280,1969864],
							[0,780,1428,2081,3552,6037,9589,15183,22374,29602,43415,63544,92830,135375,164258,221115,318406,457707,700491,1018896]
						],
						pop  : [1,1,1,3,3,5,5,7,7,7,25,25,25,25,25,25,25,25,25,25],
						variables : [ 
							[10,20,30,40,50,70,100,140,190,250,330,430,560,720,920,1160,1450,1790,2190,2650],
							[30,70,120,180,250,330,420,520,630,750,880,1020,1170,1330,1500,1700,2000,2400,2900,3500],
							[5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]
						],
						variablesname : ['耐久力','オートマタ','援軍']
					},
					220 : {
						name : '別邸',
						cost : [
							[400,936,1685,2467,4194,7191,11505,18776,33912,61043,106495,190570,340166,505021,844765],
							[136,319,573,1357,2307,3954,6327,13560,24492,44087,85196,152456,272133,456148,763014],
							[104,243,438,1110,1887,3236,5177,10430,18839,33914,66939,119786,213820,423566,708513],
							[160,374,673,1233,2097,3596,5753,9387,16956,30523,45640,81672,145786,244365,408756]
						],
						pop  : [2,1,1,5,5,5,7,7,7,10,10,10,10,10,10],
						variables : [ 
							[15,20,25,35,45,60,75,95,115,145,185,235,295,365,450],
							['1%','2%','3%','4%','5%','6%','7%','8%','9%','10%','11%','12%','13%','14%','15%'],
							[5,10,15,20,25,30,35,40,45,50,55,60,65,70,75]
						],
						variablesname : ['耐久力','ボーナス','援軍']
					},
					221 : {
						name : '領地',
						cost : [
							[0,0,0,0,0],
							[0,0,0,0,0],
							[0,0,0,0,0],
							[0,0,0,0,0]
						],
						pop  : [0,0,0,0,0],
						variables : [ 
							[1,2,2,2,4],
							['0%','20%','40%','60%','100%'],
							['1x','3.2x','6.0x','9.0x','16.0x']
						],
						variablesname : ['必要なカリスマ','防御ボーナス','資源倍率']
					},
					222 : {
						name : '屋敷',
						cost : [
							[104,243,438,1110,1887,3236,5177,10430,18839,33914,66939,119786,213820,423566,708513],
							[400,936,1685,2467,4194,7191,11505,18776,33912,61043,106495,190570,340166,505021,844765],
							[136,319,573,1357,2307,3954,6327,13560,24492,44087,85196,152456,272133,456148,763014],
							[160,374,673,1233,2097,3596,5753,9387,16956,30523,45640,81672,145786,244365,408756]
						],
						pop  : [2,2,2,3,3,4,4,5,5,5,5,5,5,5,5],
						variables : [ 
							[30,40,50,70,90,120,150,190,240,300,380,480,610,780,1000],
							[30,70,120,180,250,330,420,520,640,780,940,1140,1380,1660,2000],
							[5,10,15,20,25,30,35,40,45,50,55,60,65,70,75]
						],
						variablesname : ['耐久力','オートマタ','援軍']
					},
					
					209 : {
						name : '風のマナ',
						cost : [
							[10,25,58,173,431,1466,2493,3490,4537,5898,8119,11366,17050,25575,38362],
							[35,88,202,604,1510,2847,4839,6775,8807,11450,14434,20207,30311,45467,68199],
							[40,100,230,690,1725,3019,5132,7186,9341,12144,15787,22101,33152,49729,74593],
							[15,38,86,259,647,1294,2200,3080,4003,5204,6766,9472,14208,21312,31968]
						],
						pop  : [1,2,2,3,3,3,5,5,5,5,5,5,5,5,10],
						variables : [ [6,14,25,50,80,117,162,214,272,335,404,476,550,626,702] ],
						variablesname : ['収集量']
					},
					
					211 : {
						name : '火のマナ',
						cost : [
							[40,100,230,690,1725,3019,5132,7186,9341,12144,15787,22101,33152,49729,74593],
							[10,25,58,173,431,1466,2493,3490,4537,5898,8119,11366,17050,25575,38362],
							[35,88,202,604,1510,2847,4839,6775,8807,11450,14434,20207,30311,45467,68199],
							[15,38,86,259,647,1294,2200,3080,4003,5204,6766,9472,14208,21312,31968]
						],
						pop  : [1,2,2,3,3,3,5,5,5,5,5,5,5,5,10],
						variables     : [ [6,14,25,50,80,117,162,214,272,335,404,476,550,626,702] ],
						variablesname : ['収集量']
					},
					
					213 : {
						name : '水のマナ',
						cost : [
							[35,88,202,604,1510,2847,4839,6775,8807,11450,14434,20207,30311,45467,68199],
							[40,100,230,690,1725,3019,5132,7186,9341,12144,15787,22101,33152,49729,74593],
							[10,25,58,173,431,1466,2493,3490,4537,5898,8119,11366,17050,25575,38362],
							[15,38,86,259,647,1294,2200,3080,4003,5204,6766,9472,14208,21312,31968]
						],
						pop  : [1,2,2,3,3,3,5,5,5,5,5,5,5,5,10],
						variables     : [ [6,14,25,50,80,117,162,214,272,335,404,476,550,626,702] ],
						variablesname : ['収集量']
					},
					
					215 : {
						name : '土のマナ',
						cost : [
							[35,88,202,604,1510,3019,5132,7186,9341,12144,15787,22101,33152,49729,74593],
							[35,88,202,604,1510,3019,5132,7186,9341,12144,15787,22101,33152,49729,74593],
							[30,75,173,518,1294,2588,4399,6159,8007,10409,13532,18944,28416,42625,63937],
							[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
						],
						pop  : [0,0,0,0,0,1,1,1,1,1,2,2,2,2,3],
						variables     : [ [6,18,36,72,114,167,231,305,388,479,577,680,786,894,1003] ],
						variablesname : ['収集量']
					},
					
					216 : {
						name : 'カリスマター',
						cost : [
							[700,1120,1792,3763,5263,9834,13768,17899,23268,30249],
							[3500,5600,8960,10035,14049,14752,20652,26848,34902,45373],
							[2100,3360,5376,7526,10537,14752,20652,26848,34902,45373],
							[700,1120,1792,3763,5268,9834,13768,17899,23268,30249]
						],
						pop  : [10,5,5,10,10,15,15,20,20,25],
						variables     : [ ['0.5%','1.0%','1.5%','2.0%','2.5%','3.0%','3.5%','4.0%','4.5%','5.0%'] ],
						variablesname : ['時間短縮']
					},
					
					217 : {
						name : 'マナ変換炉',
						cost : [
							[100,334,1035,2795,6328,13288,25248,42921,64381,90134],
							[100,334,1035,2795,6328,13288,25248,42921,64381,90134],
							[50,191,592,1600,4218,8859,16832,28614,42921,60089],
							[50,191,592,1600,4218,8859,16832,28614,42921,60089]
						],
						pop  : [1,3,5,7,10,10,10,10,10,10],
						variables     : [ ['40%','42%','44%','46%','48%','50%','52%','54%','56%','60%'] ],
						variablesname : ['変換効率']
					},
					
					218 : {
						name : '温室',
						cost : [
							[2940,4704,7526,10537,14751,20652,28913,37587,48863,63523],
							[980,1568,2509,5268,7376,13768,19275,25058,32576,42348],
							[980,1568,2509,5268,7376,13768,19275,25058,32576,42348],
							[4900,7840,12544,14049,19668,20652,28913,37587,48863,63523]
						],
						pop  : [1,1,1,2,2,2,2,3,3,3],
						variables     : [
							['3%','6%','9%','12%','15%','18%','21%','24%','27%','30%'],
							['+40','+60','+80','+110','+140','+180','+220','+270','+350','+450']
						],
						variablesname : ['施設の収集量','クリスタルの収集量']
					},
					
					219 : {
						name : '水晶塔',
						cost : [
							[780,1248,1997,4193,5871,10958,15342,19944,25928,33706],
							[1560,2496,3994,6290,8806,13698,19177,24930,32410,42132],
							[1560,2496,3994,6290,8806,13698,19177,24930,32410,42132],
							[3900,6240,9984,11182,15655,16437,23013,29916,38891,50559]
						],
						pop  : [5,5,5,5,5,10,15,15,15,20],
						variables     : [
							['2.5%','5.0%','7.5%','10.0%','12.5%','15.0%','17.5%','20.0%','22.5%','25.0%'],
							['+55','+65','+75','+95','+115','+145','+185','+235','+300','+380']
						],
						variablesname : ['施設の収集量','クリスタルの収集量']
					},
					
					229 : {
						name : '時計塔',
						cost : [
							[1500,2100,2940,6629,13257,32097,64194,128388,256776,513551],
							[1600,2240,3136,7326,14653,37679,75358,150716,301432,602865],
							[2500,3500,4900,13955,27910,55821,111642,223283,446566,893133],
							[3300,3300,6468,6978,13955,13955,27910,55821,111642,223283]
						],
						pop  : [2,1,2,3,4,4,4,4,4,4],
						variables     : [ ['5%','10%','15%','20%','25%','30%','35%','40%','45%','50%'] ],
						variablesname : ['移動速度増加']
					},
					
					230 : {
						name : '錬金工房',
						cost : [
							[275,413,619,1486,2228,7521,13538,21436,44675,87725],
							[110,165,248,836,1253,6267,11282,17862,37228,73104],
							[2110,165,248,836,1253,6267,11282,17862,37228,73104],
							[55,83,124,557,836,5015,9025,14290,29784,58483]
						],
						pop  : [1,1,1,2,2,3,3,4,4,5],
						variables     : [ ['ルーク','ビショップ','ナイト','スカウト','ゴーレム','ハイスカウト','ハイルーク','ハイビショップ','ハイナイト','ハイゴーレム'] ],
						variablesname : ['錬金できる項目']
					},
					
					231 : {
						name : '防具工房 ',
						cost : [
							[150,300,585,1112,2056,3701,6477,14112,25253,40404],
							[200,400,780,1482,2742,4935,8636,17640,31566,50506],
							[340,680,1326,2519,4661,8390,14682,28223,50506,80809],
							[170,340,663,1290,2330,4195,7341,10584,18940,30303]
						],
						pop  : [2,3,3,4,4,4,5,5,5,5],
						variables     : [
							['+0.0%','+1.5%','+3.0%','+4.5%','+6.0%','+7.5%','+9.0%','+10.5%','+12.0%','+15.0%'],
							['100%','95%','90%','85%','80%','75%','70%','65%','60%','55%']
						],
						variablesname : ['ボーナス','強化時間']
					},
					
					232 : {
						name : '武器工房 ',
						cost : [
							[200,400,780,1482,2742,4935,8636,17640,31566,50506],
							[150,300,585,1112,2056,3701,6477,14112,25253,40404],
							[340,680,1326,2519,4661,8390,14682,28223,50506,80809],
							[170,340,663,1290,2330,4195,7341,10584,18940,30303]
						],
						pop  : [2,3,3,4,4,4,5,5,5,5],
						variables     : [
							['+0.0%','+1.5%','+3.0%','+4.5%','+6.0%','+7.5%','+9.0%','+10.5%','+12.0%','+15.0%'],
							['100%','95%','90%','85%','80%','75%','70%','65%','60%','55%']
						],
						variablesname : ['ボーナス','強化時間']
					},
					
					233 : {
						name : 'マナ貯蔵庫 ',
						cost : [
							[83,167,300,479,671,1044,1462,1973,2664,3596,4854,6311,8204,10255,12819,15382,18459,21228,24412,28074],
							[83,167,300,479,671,1044,1462,1973,2664,3596,4854,6311,8204,10255,12819,15382,18459,21228,24412,28074],
							[141,281,506,810,1134,1253,1754,2368,3196,4315,5825,7573,9845,12306,15382,18459,22151,21228,29294,33688],
							[83,167,300,479,671,1044,1462,1973,2664,3596,4854,6311,8204,10255,12819,15382,18459,21228,24412,28074]
						],
						pop  : [1,2,3,3,4,4,5,6,7,8,8,8,8,8,8,8,8,8,8,8],
						variables     : [ [1000,1600,2800,4600,7100,10300,14200,19000,24700,31300,38900,47500,57100,67700,79400,92200,106100,121200,137500,155000] ],
						variablesname : ['容量']
					},
					
					234 : {
						name : 'ポーン工場 ',
						cost : [
							[112,224,448,759,1214,2209,3331,4958,8091,11130],
							[107,214,428,725,1160,2110,3182,4736,7729,10632],
							[107,214,428,725,1160,2110,3182,4736,7729,10632],
							[122,244,488,826,1322,2406,3627,5400,8813,12122]
						],
						pop  : [1,1,1,1,2,2,2,3,3,3],
						variables     : [
							['00:04:51','00:03:53','00:03:07','00:02:29','00:02:00','00:01:36','00:01:17','00:01:02','00:00:49','00:00:40'],
							['00:15:00','00:12:00','00:09:37','00:07:41','00:06:09','00:04:55','00:03:56','00:03:09','00:02:31','00:02:01']
						],
						variablesname : ['ポーン','スカウト']
					},
					
					235 : {
						name : 'ルーク工場',
						cost : [
							[72,144,228,648,972,1409,2725,6744,12140,21852,39333,70800,127440,254879,509759],
							[360,720,1440,1728,2592,3758,4088,9810,17658,31784,57212,96545,173781,324392,648784],
							[72,144,228,648,972,1409,2725,6744,12140,21852,39333,70800,127440,254879,509759],
							[216,432,864,1296,1944,2819,4088,2453,4415,7946,14303,25745,46342,92683,185367]
						],
						pop  : [2,1,1,2,2,3,3,4,4,4,4,4,4,4,4],
						variables     : [
							['00:22:22','00:17:54','00:14:19','00:11:28','00:09:10','00:07:20','00:05:52','00:04:42','00:03:46','00:03:01','00:02:25','00:01:56','00:01:33','00:01:14','00:01:00'],
							['00:29:57','00:23:58','00:19:11','00:15:21','00:12:17','00:09:49','00:07:52','00:06:17','00:05:02','00:04:02','00:03:13','00:02:35','00:02:04','00:01:39','00:01:21']
						],
						variablesname : ['ルーク','ハイルーク']
					},
					
					236 : {
						name : 'ビショップ工場',
						cost : [
							[360,720,1440,1728,2592,3758,4088,9810,17658,31784,57212,96545,173781,324392,648784],
							[72,144,228,648,972,1409,2725,6744,12140,21852,39333,70800,127440,254879,509759],
							[72,144,228,648,972,1409,2725,6744,12140,21852,39333,70800,127440,254879,509759],
							[216,432,864,1296,1944,2819,4088,2453,4415,7946,14303,25745,46342,92683,185367]
						],
						pop  : [2,1,1,2,2,3,3,4,4,4,4,4,4,4,4],
						variables     : [
							['00:22:22','00:17:54','00:14:19','00:11:28','00:09:10','00:07:20','00:05:52','00:04:42','00:03:46','00:03:01','00:02:25','00:01:56','00:01:33','00:01:14','00:01:00'],
							['00:29:57','00:23:58','00:19:11','00:15:21','00:12:17','00:09:49','00:07:52','00:06:17','00:05:02','00:04:02','00:03:13','00:02:35','00:02:04','00:01:39','00:01:20']
						],
						variablesname : ['ビショップ','ハイビショップ']
					},
					
					237 : {
						name : 'ナイト工場',
						cost : [
							[72,144,228,648,972,1409,2725,6744,12140,21852,39333,70800,127440,254879,509759],
							[72,144,228,648,972,1409,2725,6744,12140,21852,39333,70800,127440,254879,509759],
							[360,720,1440,1728,2592,3758,4088,9810,17658,31784,57212,96545,173781,324392,648784],
							[216,432,864,1296,1944,2819,4088,2453,4415,7946,14303,25745,46342,92683,185367]
						],
						pop  : [2,1,1,2,2,3,3,4,4,4,4,4,4,4,4],
						variables     : [
							['00:23:58','00:19:11','00:15:21','00:12:17','00:09:50','00:07:52','00:06:17','00:05:02','00:04:02','00:03:14','00:02:35','00:02:04','00:01:39','00:01:20','00:01:04'],
							['00:33:00','00:26:24','00:21:08','00:16:54','00:13:32','00:10:49','00:08:40','00:06:56','00:05:33','00:04:26','00:03:33','00:02:51','00:02:17','00:01:49','00:01:28'],
							['00:40:00','00:32:00','00:25:37','00:20:29','00:16:24','00:13:07','00:10:30','00:08:24','00:06:43','00:05:23','00:04:18','00:03:27','00:02:45','00:02:12','00:01:46']
						],
						variablesname : ['ナイト','ハイナイト','ハイスカウト']
					},
					
					241 : {
						name : 'ゴーレム工場',
						cost : [
							[216,432,864,1224,1836,2662,3860,7457,13242,23836,42905,77229,139013,278026,556051],
							[216,432,864,1224,1836,2662,3860,7457,13242,23836,42905,77229,139013,278026,556051],
							[216,432,864,1224,1836,2662,3860,7457,13242,23836,42905,77229,139013,278026,556051],
							[72,144,288,648,972,1409,2044,2452,4414,7945,14302,25743,46338,92675,185350]
						],
						pop  : [3,2,2,3,3,4,4,5,5,5,5,5,5,5,5],
						variables     : [
							['01:40:00','01:20:00','01:04:01','00:51:13','00:40:58','00:32:47','00:26:13','00:20:59','00:16:47','00:13:26','00:10:45','00:08:36','00:06:53','00:05:30','00:04:24'],
							['03:20:00','02:40:00','02:08:01','01:42:25','01:21:56','01:05:33','00:52:26','00:41:57','00:33:34','00:26:51','00:21:29','00:17:11','00:13:45','00:11:00','00:08:48']
						],
						variablesname : ['ゴーレム','ハイゴーレム']
					},
					
					242 : {
						name : '時空兵舎',
						cost : [
							[35,53,89,147,228,336,476,653,868,1129,2032,3658,6951,13205,25090],
							[20,30,51,84,130,192,272,373,496,645,1161,2090,3971,7544,14334],
							[35,53,89,147,228,336,476,653,868,1129,2032,3658,6951,13205,25090],
							[80,120,204,337,522,767,1089,1492,1984,2580,4644,4644,15882,30177,57336]
						],
						pop  : [1,1,1,1,1,1,1,1,1,1,2,2,2,2,2],
						variables     : [ [30,60,90,120,150,190,235,285,340,400,460,530,610,700,800] ],
						variablesname : ['オートマタ上限']
					},
					
					243 : {
						name : '見張り台',
						cost : [
							[600,960,1536,2458,3932,6291,9437,14156,21233,31850,44590,62426,87397,122355,159062,206780,268814,349458,419350,503220],
							[840,1344,2150,3441,5505,8808,13212,19818,29727,44590,62426,87396,122355,171297,222686,289492,376340,489242,587090,704508],
							[600,960,1536,2458,3932,6291,9437,14156,21233,31850,44590,62426,87397,122355,159062,206780,268814,349458,419350,503220],
							[360,576,922,1475,2359,3775,5662,8493,12740,19110,26754,37456,52438,73413,95437,124068,161288,209675,251610,301932]
						],
						pop  : [1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3],
						variables     : [
							[ 'ポーン','ルーク','','ビショップ','','ナイト','','ハイルーク','','ハイビショップ','','ハイナイト','','ゴーレム','','ハイゴーレム','','スカウト/ハイスカウト','','キャラ' ],
							[ 30,70,120,180,250,330,420,520,630,750,880,1020,1170,1330,1500,1680,1870,2070,2280,2500 ]
						],
						variablesname : ['種類','数']
					},
					
					244 : {
						name : '大時空兵舎',
						cost : [
							[200,320,512,768,1152,1728,2419,3387,4741,6637,8628,11217,14582,18956,25817,32271,42172,52715,66009,79211],
							[114,183,293,439,658,987,1382,1935,2709,3793,4930,6409,8332,11735,16429,22003,29337,38963,49506,62708],
							[200,320,512,768,1152,1728,2419,3387,4741,6637,8628,11217,14582,18956,25817,32271,42172,52715,66009,79211],
							[438,701,1121,1682,2523,3784,5298,7418,10385,14538,18900,24570,31941,40620,49286,60141,69675,84803,93512,108914]
						],
						pop  : [1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3],
						variables     : [ [39,78,117,156,195,247,306,371,442,520,598,689,793,910,1040,1183,1339,1508,1690,1885] ],
						variablesname : ['オートマタ上限']
					},
					
					246 : {
						name : '大時計塔',
						cost : [
							[2884,4614,7382,11811,18898,28347,42521,63781,89294,125011,175015,227520,295776,384509,512678,645974,812082,1018794,1275708,1594635],
							[4486,7177,11483,18373,29397,44096,66143,99215,138901,194461,272246,353920,460096,598125,692116,830539,959734,1151680,1382016,1658420],
							[5977,9484,15174,24279,38846,58269,87404,131105,183548,256967,359754,467680,607984,790379,897187,1045863,1218123,1417453,1647789,1913561],
							[2723,4357,6972,11155,17848,26772,40158,60238,84333,118066,165292,214880,279344,363147,461410,553692,701344,841613,1009935,1211922]
						],
						pop  : [1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2],
						variables     : [ ['距離×0.1%','距離×0.2%','距離×0.3%','距離×0.4%','距離×0.5%','距離×0.6%','距離×0.7%','距離×0.8%','距離×0.9%','距離×1.0%','距離×1.1%','距離×1.2%','距離×1.3%','距離×1.4%','距離×1.5%','距離×1.6%','距離×1.7%','距離×1.8%','距離×1.9%','距離×2.0%'] ],
						variablesname : ['移動速度増加']
					}
				};
				// レベル毎の情報
				var facilityid = j$('td.imgs img').attr('src').match( /facility_(\d+)\.png/ )[1];
				var level = j$('table[summary="object"] .mainTtl').text().match( /レベル(\d+)/ )[1];
				if ( facilityid in FacilitiesData ) {
					var commonname = ['レベル','風のマナ','火のマナ','水のマナ','土のマナ','発展度'];
					var maxlevel = FacilitiesData[facilityid].variables[0].length;
					var levelup = -1;
					if ( maxlevel>level) {
						if ( j$('.lvupFacility').text().match( /すでに最大レベル/ ) ) { levelup = maxlevel; }
						else { levelup = j$('#gray02Wrapper').text().match( /レベル「(\d+)」/ )[1]-1; }
					}
					var table = '<table class="commonTables" style="width:100%;text-align:right"><tbody>';
					table += '<tr>'
					table += commonname.concat(FacilitiesData[facilityid].variablesname).join2( '<th class="mainTtl6">', '</th>' );
					table += '</tr>';
					var pop = 0;
					for (var i=0;i<maxlevel;i++) {
						var isCurrentLevel = (i+1==level);
						if ( isCurrentLevel ) { table += '<tr style="font-weight:bold;">'; }
						else if ( i+1>level && i+1<=levelup ) { table += '<tr style="font-weight:bold;font-style:italic;">'; }
						else { table += '<tr>'; }
						table += '<th class="ttl4">' + ( (i+1>=level && i+1<=levelup) ? '→' + (i+1) + '' : (i+1) ) + '</th>';
						table += '<td>' + FacilitiesData[facilityid].cost[0][i] + '</td>';
						table += '<td>' + FacilitiesData[facilityid].cost[1][i] + '</td>';
						table += '<td>' + FacilitiesData[facilityid].cost[2][i] + '</td>';
						table += '<td>' + FacilitiesData[facilityid].cost[3][i] + '</td>';
						pop += FacilitiesData[facilityid].pop[i];
						table += '<td>' + pop + '</td>';
						for (var j=0;j<FacilitiesData[facilityid].variables.length;j++) {
								table += '<td>' + FacilitiesData[facilityid].variables[j][i] + '</td>';
						}
						table += '</tr>';
					}
					table += '</tbody></table>';
					j$('div.back').before( table );
				}
			}
			
			// 施設機能改善
			if ( checkOption('mahoujin') && j$('#whiteWrapper h2').text().match(/.の魔法陣/) ) {
				var $gain = j$('table[summary="object"] tr:nth-child(5) td.contents');
				var mValue = $gain.text().match( /\:(\d+).+\:(\d+)/ );
				var gain = mValue[2] - mValue[1];
				if ( reqres[3] == 0 ) { gain /= 2; }
				var totalres = reqres[0]+reqres[1]+reqres[2]+reqres[3]/2;
				$gain.html( $gain.text() + '<br>コスト回収時間: 約' + getTimeText( totalres/gain*3600 ) + '' );
			}
			
			if ( checkOption('henkanro') && j$('#whiteWrapper h2').text() == 'マナ変換炉') {
				j$('#select').attr('selectedIndex',4).trigger('change').hide().after('土のマナ');
				j$('#select2 option[value="104"]').remove();
				j$('input[name="confirm_btn"]').parent().parent().before( '<tr><th class="ttl2">欲しいマナの量</th><td><input size="8" id="tc2" type="text"></td></tr>' );
				var rate = j$('table[summary="object"] tr:nth-child(5) td.contents').text().match( /(\d+)%/ )[1] / 100;
				j$('#tc2').change(function() {
					j$('#tc').val( Math.ceil( j$('#tc2').val() / rate ) );
				});
				j$('#tc').change(function() {
					j$('#tc2').val( Math.floor( j$('#tc').val() * rate ) );
				});
				j$('#resource_num').bind( 'click', function() {
					j$('#tc').trigger('change');
				});
			}
		}
		
		if ( DesignMode && checkOption('facilitydata') && location.pathname == '/territory_proc.php' ) {
			var level = j$('table[summary="object"] .mainTtl').text().match( /レベル(\d+)/ )[1];
			var maxlevel = 5;
			var levelup = level;
			var variables = [ 
					[1,2,2,2,4],
					['0%','20%','40%','60%','100%'],
					['1x','3.2x','6.0x','9.0x','16.0x']
				];
			var table = '<table class="commonTables" style="width:100%;text-align:right"><tbody>';
			table += '<tr>'
			table += ['レベル','必要なカリスマ','防御ボーナス','資源倍率'].join2( '<th class="mainTtl6">', '</th>' );
			table += '</tr>';
			for (var i=0;i<maxlevel;i++) {
				var isCurrentLevel = (i+1==level);
				if ( isCurrentLevel ) { table += '<tr style="font-weight:bold;">'; }
				else if ( i+1>level && i+1<=levelup ) { table += '<tr style="font-weight:bold;font-style:italic;">'; }
				else { table += '<tr>'; }
				table += '<th class="ttl4">' + ( (i+1>=level && i+1<=levelup) ? '→' + (i+1) + '' : (i+1) ) + '</th>';
				for (var j=0;j<variables.length;j++) {
						table += '<td>' + variables[j][i] + '</td>';
				}
				table += '</tr>';
			}
			table += '</tbody></table>';
			j$('#tMenu').append( table );
		}
		
		if( checkOption('facilitynew') && location.pathname == '/facility/select_facility.php' ) {
			var ul = '<ul id="statMenu">';
			ul += '<li><a class="toggleall" href="#" style="color:black">全部</a></li>';
			j$('table[summary="object"]').each(function() {
				var name = j$('.mainTtl', this).text();
				this.setAttribute( 'id', name );
				ul += '<li><a class="toggleobject" href="#">' + name + '</a></li>';
			});
			ul += '</ul>';
			j$('.sysMes').after(ul);
			j$('.toggleobject').click(function() {
				j$('table[summary="object"]').hide();
				j$('#' + j$(this).text()).show();
				j$('.toggleobject, .toggleall').css('color','');
				j$(this).css('color','black');
				return false;
			});
			j$('.toggleall').click(function() {
				j$('table[summary="object"]').show();
				j$('.toggleobject').css('color','');
				j$(this).css('color','black');
				return false;
			});
		}
		
		////////////////////
		// デッキ
		////////////////////
		if ( location.pathname == '/card/deck.php' ) {
			if ( checkOption('cardrecovery') ) {
				function setTensionRestTime(e,m) {
					var $Tension = j$('div.para', e);
					var rest = ((m==0)?500:300) - parseInt($Tension.html());
					if ( rest > 0 ) { $Tension[0].innerHTML += '(あと'+getTimeText(rest*216)+')';}
				}
				function setHPRestTime(e,m) {
					var hp = parseInt(j$('span.status_hp_txt', e).text().split('/')[0]);
					var level = parseInt(j$('span.level', e).text());
					var rest = 0;
					if ( hp < 100 ) { 
						rest = (level <= 5) ? Math.pow(2, level - 2) * (100 - hp) / 100 :
									 (level <= 10) ? 4 * (level - 3) * (100 - hp) / 100 :
									 (level + 20) * (100 - hp) / 100; // ブラウザ三国志Beyondのソースから拝借しています
						j$('span.status_hp_txt', e).attr( 'title', 'あと'+getTimeText(rest*3600) );
						if ( m==1 ) { j$('dl dd:nth-child(6)', e).text( '治療中 (あと' + getTimeText(rest*3600) + ')' ); }
					}
				}
				
				j$('#cardListDeck div.cardColmn').each(function() {
					setTensionRestTime(this,0);
					setHPRestTime(this,0);
				});
				
				j$('#cardFileList div.cardColmn').each(function() {
					setTensionRestTime(this,1);
					setHPRestTime(this,1);
					
					//テンションゲージの幅
					j$('div.gageCover', this).css( 'text-align' , 'left' );
					j$('div.gage', this).width( 80 );
					j$('div.gageCover img', this).width( 80 );
					j$('div.gageIn img', this).width( j$('div.gageIn img', this).width()-54 );
				});
			}
			
			//セット先自動選択
			if ( checkOption('cardset') ) {
				var id = j$('div.cardColmn select:first option').filter(function() { return j$(this).text() == CurrentVillage['name']; }).val();
				try {
					j$('div.cardColmn select').val(id).trigger('change');
				} catch(err) {}
			}
		}

		// ステータス強化
		if ( checkOption('statuspoint') && location.pathname == '/card/status_info.php' ) {
			var $lines = j$('tr.statusPoints td.line:nth-child(3)');
			var names = [ 'attack', 'defense', 'intellect', 'move_speed' ];
			var value = j$('#status_table > tbody > tr:nth-child(3) > td:first').text();
			for ( i=0; i<=3; i++ ) {
				j$($lines[i]).append(
					'<input value="全部" onclick="statusChange(\'' + names[i] + '_pt\', ' + (i+4) + ', 1, ' + value + ')" type="button">' +
					'<input value="×" onclick="statusChange(\'' + names[i] + '_pt\', ' + (i+4) + ', 1, parseInt(j$(\'#hidden_' + names[i] + '_pt\').val())*-1 )" type="button">'
				);
			}
			j$('input[value="+5"]').hide();
			j$('#status_table').append('<colgroup><col style="width:44%" /><col style="width:8%" /><col style="width:20%" /><col style="width:14%" /><col style="width:14%" /></colgroup>');
			$lines.css('text-align','right');
		}
		
		////////////////////
		// 同盟
		////////////////////
		if( checkOption('allyranking') && location.pathname == '/alliance/info.php' ) {
			var $member = j$('table[summary="件名"] > tbody > tr:nth-child(6) > td:nth-child(4)');
			var member = $member.text().match(/(\d+)\/(\d+)/);
			var $kifu = j$('table[summary="件名"] > tbody > tr:nth-child(7) > td:nth-child(2)');
			var kifu = $kifu.text().match(/(\d+)\/(\d+)/);
			$kifu.html( $kifu.text() + '<br>一人あたり: ' + Math.ceil(kifu[2]/member[1]) + ' <br> LvUPまで: あと' + ( kifu[2] - kifu[1] ) );
			
			var $l = j$('table[summary="ランキング"] > tbody > tr:gt(1)').filter(function() { return j$('a',this).text() == My.name; });
			$l.children().eq(1).css('font-weight','bold');
			$l.children().eq(0).text( '→' + $l.children().eq(0).text() );
			
			j$('table[summary="マナの寄付"] .mainTtl').text( 'マナの寄付 （現在' + $l.children().eq(3).text() + '）' );
		}
		
		////////////////////
		// オートマタ管理
		////////////////////
		if ( checkOption('attacktime') ) {
			if ( location.pathname == '/facility/unit_status.php' ) {
				var attackarmies = {};
				var n = getDate(Server.getTime()).getTime();
				j$.each(Storage.get('attackarmies'), function(chara, value) {
					var d = getDate(value['time']).getTime();
					if ( n < d && value['from'] != CurrentVillage['coordinate'] ) { attackarmies[chara] = value; }
				});
				j$('table[summary="出撃中の部隊"] table.commonTablesNoMG').each(function() {
					var time = j$(this).parent().parent().prev().find('> td:nth-child(2)').text().match(/\d+\-\d+\-\d+ \d+:\d+:\d+/)[0];
					var coord = j$(this).parent().parent().prev().prev().find('> td:nth-child(3)').text().match(/\(([\-0-9]+,[\-0-9]+)\)/)[1];
					var chara = j$(this).parent().parent().prev().find('> td:nth-child(4) a').text();
					var army = [];
					j$('td.digit:lt(11)', this).each(function() {
						army.push(parseInt(j$(this).text()));
					});
					attackarmies[chara] = {
						'time' : time,
						'from' : CurrentVillage['coordinate'],
						'to'   : coord,
						'army' : army,
					};
				});
				Storage.set('attackarmies',attackarmies);
			}
			if ( location.pathname == '/facility/castle_send_troop.php' && j$(".fighting_about").length > 0 ) {
				var attackarmies = {};
				var n = getDate(Server.getTime()).getTime();
				j$.each(Storage.get('attackarmies'), function(chara, value) {
					var d = getDate(value['time']).getTime();
					if ( n < d ) { attackarmies[chara] = value; }
				});
				Storage.set('attackarmies',attackarmies);
				var time = j$('.fighting_about td').text().match(/到着まで\:  (\d\d\:\d\d\:\d\d)/)[1];
				function calcStartTime(datastring){
					var s = getSeconds(time);
					var d = getDate(datastring).getTime();
					var n = getDate(Server.getTime()).getTime();
					if ( n + s*1000 > d ) {
						return '間に合わない';
					} else {
						return calcDate( datastring, -s-1 );
					}
				}
				var name = ['ポーン','ルーク','ビショップ','ナイト','ハイルーク','ハイビショップ','ハイナイト','スカウト','ハイスカウト','ゴーレム','ハイゴーレム'];
				var coord = j$(".fighting_about strong").text().match(/\(([\-0-9]+,[\-0-9]+)\)/)[1];
				var table = '<table class="commonTables"><colgroup><col class="w100"/><col class="w300"/><col class="w180"/><col class="w180"/></colgroup><tbody>';
				table += '<tr><th class="mainTtl" colspan="13">出発時間計算</th></tr>';
				var table2 = '';
				j$.each(attackarmies, function(chara, value) {
					if ( value['to'] == coord ) {
						table2 += '<tr><td>' + chara + '</td><td>';
						j$.each(value['army'], function(index, count) {
							if ( count > 0 ) { table2 += name[index] + count + ' '; }
						});
						table2 += '</td><td>' + value['time'] + '</td>';
						table2 += '<td>' + calcStartTime(value['time']) + '</td>';
						table2 += '</tr>';
					}
				});
				if ( table2.length > 0 ) {
					table += '<tr><th class="ttl2" colspan="2">出撃中の部隊</th><th class="ttl2">到着時間</th><th class="ttl2">最遅出発時間</th></tr>';
					table +=table2;
				}
				table += '<tr><th class="ttl5" colspan="2">手動入力</td><td style="margin:0 5px"><input id="arrivetime" placeholder="yyyy-mm-dd hh:mm:ss" /></td><td id="starttime"></td></tr>';
				table += '</tbody></table>';
				j$('#facility_char').after(table);
				j$('#arrivetime').change(function() {
					var d = j$(this).val().match(/\d\d\d\d\-\d+\-\d+ +\d+\:\d+\:\d+/);
					j$('#starttime').text( (d.length > 0)?calcStartTime(d[0]):'' );
				});
			}
		}
		
		////////////////////
		// クエスト
		////////////////////
		if( checkOption('questoverflow') && location.pathname == '/quest/' ) {
			var $reward = j$('.reward td:nth-child(2)');
			if ( $reward.length == 4 ) {
				var overflow = false;
				for (var i=0;i<=3;i++) {
					if ( mana.now[i] + parseInt(j$($reward[i]).text()) >= mana.max[i] ) { 
						j$($reward[i]).css( 'color', 'red' );
						overflow = true; 
					}
				}
				var $accept = j$('a[title="報酬を受け取る"]');
				if ( overflow && $accept.length > 0 ){
					$accept.click(function() {
						return confirm('倉庫の空き容量が不足しています\n本当に報酬を受け取りますか？');
					});
				}
			}
		}
		
		////////////////////
		// コミュ
		////////////////////
		if ( checkOption('textcoord') || checkOption('texturl') ) {
			function setLinks( content ) {
				var txt = j$(content).html();
				var regURL = /https*\:\/\/[A-Za-z0-9\-_\/\.\#\?\=\&\;]+/gi ;
				var regCoord = /(\-{0,1}[0-9０-９]{1,3}) *[,、・] *(\-{0,1}[0-9０-９]{1,3})/g ;
				if ( checkOption('textcoord') ) { txt = txt.replace( regURL, '<a href="$&" target="_blank" style="display:inline">$&</a>' ); }
				if ( checkOption('texturl')   ) { txt = txt.replace( regCoord, '<a href="/map.php?x=$1&y=$2#ptop" style="display:inline">$&</a>' ); }
				j$(content).html( txt );
			}
			
			//ひとこと
			j$('#commentList td:nth-child(3)').each(function() {
				setLinks(this);
			});
			if ( location.pathname == '/bbs/res_view.php' || location.pathname == '/bbs/personal_res_view.php' ) { // 掲示板
				j$('.threadTtl, table[summary="件名"] tr:nth-child(2) td, td.contents').each(function() {
					setLinks(this);
				});
			} else if ( location.pathname == '/alliance/chat_view.php' ) { // 同盟ひとこと掲示板
				j$('p.hitokoto').each(function() {
					setLinks(this);
				});
			} else if ( location.pathname == '/message/detail.php' ) { // メール
				j$('table.commonTables tr:nth-child(4) td, table.commonTables tr:nth-child(5) td').each(function() {
					setLinks(this);
				});
			} else if ( location.pathname == '/user/' || location.pathname == '/user/change/change.php' ) { // プロフィール
				j$('.show_comment_cell').each(function() {
					setLinks(this);
				});
			}
		}
		
		if ( checkOption('coordmenu') && location.pathname != '/big_map.php' ) {
			j$('#box a[href*="/map.php"], #box a[href*="/land.php"]').each(function() {
				var coord = getCoord(j$(this).attr('href'));
				var links = [
					['表示', '/land.php?'+coord[0] ],
					['地図', '/map.php?'+coord[0] ],
					['攻撃 (距離'+ getDistance(coord[1],coord[2]) + ')', '/facility/castle_send_troop.php?'+coord[0] ],
				]
				createExtraMenu(this,links);
			});
		}
		
		if ( checkOption('usermenu') && location.pathname != '/big_map.php' ) {
			j$('#box a[href*="/user/?user_id="]').each(function() {
				var user_id = j$(this).attr('href').match(/user_id=(\d+)/)[1];
				var links = [
					['プロフィール', '/user/?user_id=' + user_id ],
					['個人掲示板', '/bbs/personal_topic_view.php?user_id=' + user_id ],
					['メッセージを送る', '/message/new.php?user_id=' + user_id ],
				]
				createExtraMenu(this,links);
			});
		}
		
		// CP機能
		if ( checkOption('hidecp') ) {
			j$( [
				'#deck_top_item',
				'#actionLog .build',
				'.useCp',
				'#card_extend_wrapper',
				'#deck_top_item ul, #deckcost_up ul',
				'.lvupFacility .sub',
				'.lvupFacility p[class=""]',
				'.commonTablesReserveAttack'
			].join(',') ).addClass('cpkinou').hide();
			if ( location.pathname == '/card/deck.php' ) {
				j$('.navi').append('<li style="float:right">デッキコスト: ' + j$('.deckcost').text() + '</li>');
			}
		}
		
		// 外部リンク
		if ( Server.version == 'm' && checkOption('skipextlink') ) {
			j$('a[href*=http://mixi.jp/navigate_to_external_site_from_appli.pl]').each(function() {
				j$(this).attr('href', decodeURIComponent( j$(this).attr('href').match(/url=([^&]*)/)[1] ) );
			});
		}
	}
	
	/* Megamiengage Main end */
	
}

/* Browser fixes begin */

if ( !!window.chrome ) {
	var script = document.createElement('script');
	script.setAttribute("type", "application/javascript");
	script.textContent = '(' + Main + ')();';
	document.body.appendChild(script);
	document.body.removeChild(script);
} else {
	Main();
}

/* Browser fixes end */
